package cn.itcast.fileoperation;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private Button btn_read;
    private Button btn_write;
    private TextView tv_content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_read = (Button) findViewById(R.id.btn_read);
        btn_write = (Button) findViewById(R.id.btn_write);
        tv_content = (TextView) findViewById(R.id.tv);
        btn_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //写文件
                String fileName = "data.txt";
                String content = "helloworld";
                FileOutputStream fos = null;
                try{
                    //String fileDir = Environment.getDataDirectory().toString();
                    fos = openFileOutput(fileName, MODE_PRIVATE);
                    fos.write(content.getBytes());
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try{
                        if(fos != null){
                            fos.close();
                        }
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读文件
                String fileName = "data.txt";
                String content = "";
                FileInputStream fis = null;
                try{
                    fis = openFileInput(fileName);
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    content = new String(buffer);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try{
                        if(fis != null){
                            fis.close();
                        }
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
                tv_content.setText(content);
            }
        });
    }
}